<template>
  <div class="flex column margin-t-15 no-wrap" style="height: 94%">
    <!-- 搜索栏 -->
    <ListSearch :createUserList="createUserList" @search="search" :taskType="taskType" :driverListObj="driverListObj" />
    <!-- 表格 -->
    <div class="flex-1 padding-l-20 padding-r-20" style="height: 0">
      <q-table
          :data="tableData"
          :columns="columns"
          row-key="prodId"
          class="scroll stick-last-col full-height"
          :loading="tableLoading"
          :pagination="pagination"
          hide-bottom
          separator="cell"
          no-data-label="暂无数据"
          color="primary"
      >
        <template v-slot:header-cell-taskState="props">
          <q-th :props="props">
            {{ props.col.label }}
            <span>
            <q-icon name="iconfont icontubiao-72" class="text-grey"
                    style="margin-left: 5px;margin-top: -3px;font-size: 14px"/>
            <q-tooltip max-width="500px">
              <div>单次任务：</div>
              <div>1）待开始：未到开始时间，任务还没开始</div>
              <div>2）执行中：开始执行但是还没执行完成</div>
              <div>3）已完成：任务执行完成</div>
              <div>4）失效：任务未执行完成，但是不在有效时间范围</div>
              <div>5）已关闭：进行中的任务被关闭了</div>
              <div v-if="!showCycleTask">6）等待中：任务已开始，但在等待排在此任务之前的网关执行完任务</div>
              <div v-if="showCycleTask">
                <div>周期任务：</div>
                <div>1）待开始：未到开始时间，任务还没开始</div>
                <div>2）执行中：任务在有效期内，并且本次任务正在执行</div>
                <div>3）准备就绪：任务在有效期内，等待下一次任务开始</div>
                <div>4）失效：任务不在有效时间范围</div>
                <div>5）已关闭：该周期性的任务被关闭了</div>
              </div>
            </q-tooltip>
          </span>
          </q-th>
        </template>
        <template v-slot:header-cell-startDate="props">
          <q-th :props="props">
            {{ props.col.label }}
            <span>
            <q-icon name="iconfont icontubiao-72" class="text-grey"
                    style="margin-left: 5px;margin-top: -3px;font-size: 14px"/>
            <q-tooltip max-width="500px">
              这个任务第一次开始执行的时间
            </q-tooltip>
          </span>
          </q-th>
        </template>
        <template v-slot:header-cell-valiDate="props">
          <q-th :props="props">
            {{ props.col.label }}
            <span>
            <q-icon name="iconfont icontubiao-72" class="text-grey"
                    style="margin-left: 5px;margin-top: -3px;font-size: 14px"/>
            <q-tooltip max-width="500px">
              在这个时间之前，该任务是有效的
            </q-tooltip>
          </span>
          </q-th>
        </template>
        <template v-slot:body-cell-taskState="props">
          <q-td v-if="taskStatusObj[props.row.taskState]">
            <div class="status" :class="getTaskClass(props.row.taskState)"></div>
            {{ taskStatusObj[props.row.taskState] }}
          </q-td>
          <q-td v-else>--</q-td>
        </template>
        <template v-slot:body-cell-operations="props">
          <q-td class="operations bg-white" style="width: 100px">
            <q-btn
                flat
                color="primary"
                class="table-flat-btn"
                @click="toDetail(props.row)">
              详情
            </q-btn>
            <q-btn
                flat
                color="primary"
                @click="toEdit(props.row)"
                :disable="props.row.taskState+'' !== '1'"
                class="table-flat-btn">
              编辑
            </q-btn>
            <q-btn
                flat
                color="primary"
                :disable="props.row.taskState+'' !== '1'"
                @click="deleteTask(props.row)"
                class="table-flat-btn">
              删除
            </q-btn>
            <q-btn
                flat
                color="primary"
                @click="closeTask(props.row)"
                :disable="disableClose(props.row)"
                class="table-flat-btn">
              关闭
            </q-btn>
          </q-td>
        </template>
      </q-table>
    </div>
    <div class="full-width">
      <pagination
          style="position: relative;padding: 20px"
          v-model="pagination.page"
          :page-size="pagination.rowsPerPage"
          :total="pagination.rowsNumber"
          @changePage="onPageChange"
          @changePageSize="onPageSizeChange"
      >
      </pagination>
    </div>
  </div>
</template>

<script>
import ListSearch from './list-search.vue'
import Pagination from 'src/components/pagination'
import {
  closeTask,
  getBoxTask,
  getCreateUser,
  getLocalDriverVersionList,
  removeTask
} from '../../../../../boot/miot/task'
import { cycleObj, taskStatusObj, taskTypeObj } from '../constant'
import moment from 'moment'

export default {
  name: 'task-reboot',
  components: {
    ListSearch,
    Pagination
  },
  props: {
    taskType: {
      type: String,
      default: ''
    }
  },
  data () {
    return {
      cycleObj: cycleObj,
      taskStatusObj: taskStatusObj,
      taskTypeObj: taskTypeObj,
      tableData: [],
      tableLoading: false,
      // 表格分页配置
      pagination: {
        // 页码
        page: 1,
        // 每页条数
        rowsPerPage: 15,
        // 总条数
        rowsNumber: 0
      },
      createUserObj: {},
      queryParams: {
        taskState: '',
        exeCycle: '',
        startRange: null,
        ownerId: '',
        driver: '',
        version: ''
      },
      driverListObj: {}
    }
  },
  computed: {
    createUserList () {
      return Object.keys(this.createUserObj).map(item => ({
        label: this.createUserObj[item],
        value: item
      }))
    },
    columns () {
      if (this.taskType === '4') {
        return [{ name: 'taskTypeName', label: '任务类型', align: 'left', field: 'taskTypeName' },
          { name: 'boxNum', label: '网关数量', align: 'left', field: 'boxNum' },
          { name: 'taskState', label: '任务状态', align: 'left', field: 'taskState' },
          { name: 'exeCycle', label: '执行周期', align: 'left', field: 'exeCycle' },
          { name: 'startDate', label: '开始时间', align: 'left', field: 'startDate' },
          { name: 'valiDate', label: '有效期至', align: 'left', field: 'valiDate' },
          { name: 'driverName', label: '驱动名称', align: 'left', field: 'driverName' },
          { name: 'driverVersion', label: '版本号（升级到）', align: 'left', field: 'driverVersion' },
          { name: 'successNum', label: '成功数量', align: 'left', field: 'successNum' },
          { name: 'errorNum', label: '失败数量', align: 'left', field: 'errorNum' },
          { name: 'remark', label: '任务说明', align: 'left', field: 'remark' },
          { name: 'createTime', label: '创建时间', align: 'left', field: 'createTime' },
          { name: 'ownerName', label: '创建人', align: 'left', field: 'ownerName' },
          { name: 'operations', label: '操作', align: 'left', field: 'operations' }]
      }
      return [
        { name: 'taskTypeName', label: '任务类型', align: 'left', field: 'taskTypeName' },
        { name: 'boxNum', label: '网关数量', align: 'left', field: 'boxNum' },
        { name: 'taskState', label: '任务状态', align: 'left', field: 'taskState' },
        { name: 'exeCycle', label: '执行周期', align: 'left', field: 'exeCycle' },
        { name: 'startDate', label: '开始时间', align: 'left', field: 'startDate' },
        { name: 'valiDate', label: '有效期至', align: 'left', field: 'valiDate' },
        { name: 'successNum', label: '成功数量', align: 'left', field: 'successNum' },
        { name: 'errorNum', label: '失败数量', align: 'left', field: 'errorNum' },
        { name: 'remark', label: '任务说明', align: 'left', field: 'remark' },
        { name: 'createTime', label: '创建时间', align: 'left', field: 'createTime' },
        { name: 'ownerName', label: '创建人', align: 'left', field: 'ownerName' },
        { name: 'operations', label: '操作', align: 'left', field: 'operations' }
      ]
    },
    showCycleTask () {
      return this.taskType !== '4'
    }
  },
  watch: {
    taskType (val) {
      if (val) {
        Object.assign(this.queryParams, this.$options.data.call(this).queryParams)
        this.getTableData()
      }
    }
  },
  created () {
    this.init()
  },
  methods: {
    init () {
      getCreateUser().then(res => {
        this.createUserObj = res.data
        this.getTableData()
        this.getLocalDriverVersionList()
      })
    },
    getTableData () {
      const params = {
        taskType: this.taskType,
        pageNum: this.pagination.page,
        pageSize: this.pagination.rowsPerPage,
        ownerId: this.queryParams.ownerId,
        taskState: this.queryParams.taskState,
        exeCycle: this.queryParams.exeCycle,
        driverVersion: this.queryParams.version,
        driverName: this.queryParams.driver,
        startDate: this.queryParams.startRange ? moment(this.queryParams.startRange[0]).format('YYYY-MM-DD HH:mm:ss') : '',
        endDate: this.queryParams.startRange ? moment(this.queryParams.startRange[1]).format('YYYY-MM-DD HH:mm:ss') : ''
      }
      this.tableLoading = true
      getBoxTask(params).then(res => {
        const data = res.data
        this.pagination.rowsNumber = data.total
        const list = data.list
        this.tableData = list.map(item => {
          return {
            ...item,
            exeCycle: this.cycleObj[item.exeCycle],
            ownerName: this.createUserObj[item.ownerId],
            taskTypeName: this.taskTypeObj[this.taskType],
            startDate: moment(item.startDate).format('YYYY-MM-DD HH:mm:ss'),
            valiDate: moment(item.valiDate).format('YYYY-MM-DD HH:mm:ss'),
            createTime: moment(item.createTime).format('YYYY-MM-DD HH:mm:ss')
          }
        })
      }).finally(() => {
        this.tableLoading = false
      })
    },
    getLocalDriverVersionList () {
      getLocalDriverVersionList().then(res => {
        this.driverListObj = res.data
      })
    },
    // 搜索
    search (queryParams) {
      this.pagination.page = 1
      this.queryParams = queryParams
      this.getTableData()
    },
    // 重置
    resetSearch () {
      Object.assign(this.queryParams, this.$options.data.call(this).queryParams)
    },
    // 跳转到详情页面
    toDetail (row) {
      this.$router.push({ name: 'taskDetail', query: { id: row.id, taskType: this.taskType } })
    },
    // 删除任务
    deleteTask (row) {
      this.$q.dialog({
        title: `<p class="dialog-notice-title"><i class="iconfont icontubiao-28"></i>
          确定要删除任务吗？</p>`,
        html: true,
        ok: {
          unelevated: true,
          label: '确认'
        },
        cancel: {
          unelevated: true,
          outline: true,
          label: '取消'
        }
      }).onOk(() => {
        removeTask(row.id).then(() => {
          this.$message.success('删除任务成功')
          this.getTableData()
        })
      })
    },
    // 关闭成功
    closeTask (row) {
      closeTask(row.id).then(() => {
        this.$message.success('关闭任务成功')
        this.getTableData()
      })
    },
    // 关闭是否禁用
    disableClose (row) {
      // 单次任务：仅执行中状态可关闭；周期任务：执行中和准备就绪可关闭
      if (row.exeCycle === 1) {
        return row.taskState !== 2
      } else {
        return !(row.taskState === 2 || row.taskState === 3)
      }
    },
    // 去编辑
    toEdit (row) {
      this.$router.push({
        name: 'addManage',
        query: {
          id: row.id,
          taskType: this.taskType
        }
      })
    },
    getTaskClass (num) {
      const obj = {
        '1': 'toBegin',
        '2': 'starting',
        '3': 'readying',
        '4': 'finished',
        '5': 'loseEfficacy',
        '6': 'close'
      }
      return obj[num]
    },
    /**
     * on 分页组件的每页条数发生改变
     * @param val 每页条数
     */
    onPageSizeChange: function (val, page) {
      this.pagination.rowsPerPage = val
      page && (this.pagination.page = page)
      this.getTableData(this.queryParams)
    },

    /**
     * on 分页组件的页码发生改变
     * @param val 页码
     */
    onPageChange: function (val) {
      this.pagination.page = val
      this.getTableData(this.queryParams)
    }
  }
}
</script>

<style scoped lang="scss">
.toBegin {
  background: #5f77fd;
}

.starting {
  background: $positive;;
}

.readying {
  background: $secondary;
}

.loseEfficacy {
  background: $warning;
}

.finished {
  background: #999999;
}

.close {
  background: #666666;
}
</style>
